import {action, observable, runInAction} from "mobx";
import {BaseResInterface, BaseResInterfaceWithData, sendGetRequest} from "../../../net";
import {CategoryInterface} from "../../../net/instance/CommenModelInstance";
import {defaultArr} from "../../../util";
import {realm} from "../../../dao";
import Category from "../../../component/page/main/category";
import * as _ from "lodash";


interface Main {

}

export class MainStore {

    @observable categories: CategoryInterface[] = defaultArr;

    @action.bound
    async getCategories() {
        const {data} = await sendGetRequest<BaseResInterfaceWithData<CategoryInterface[]>>("main/getProductCategories");
        //2为首页分类 其他分类按照名称排序
        const categories = data.sort(function (pre,cur) {
           if(pre.id === 2||cur.id === 2)return 1;
           return cur.name < pre.name?1:-1;
        });
        runInAction(() => {
            this.categories = categories;
        });
        realm.write(() => {
            categories.forEach((category) => {
                realm.create<CategoryInterface>("Category", category, true);
            })
        });
    }

    constructor() {
        this.categories = _.toArray<CategoryInterface>(realm.objects<CategoryInterface>("Category")) ;
    }

}

const MainStoreInstance = new MainStore();
export default MainStoreInstance